package ue.security;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import ue.com.mapper.RoleDao;
import ue.com.mapper.UserDao;
import ue.entity.system.Role;
import ue.entity.system.User;
public class LocalUserDetailService implements UserDetailsService {
    @Autowired
	UserDao userDao;
    
    @Autowired
    RoleDao roleDao;
    
	@Override
	public UserDetails loadUserByUsername(String loginName)
			throws UsernameNotFoundException {
		LocalUserDetail userDetail = null;
		 User user = this.userDao.getByLoginName(loginName);
		 if(user!=null){
		 
		 List<Role> roles = this.roleDao.getUserRolesByUserId(user.getId());
		 
		 List<LocalRole> localAuthoritys = this.toAuthoritys(roles);
				 
		 userDetail = new LocalUserDetail(user, localAuthoritys);
		 }
         
         
		return userDetail;
	}
	
	
	private List<LocalRole> toAuthoritys(List<Role> roles){
		
		List<LocalRole> localAuthoritys = new ArrayList<LocalRole>();
		
		
		for(Role role : roles){
			
			LocalRole localRole =  new LocalRole(role);
			
			localAuthoritys.add(localRole);
		}
		return localAuthoritys;
		
		
		
	}
	

}
